<template>
  <div>
    <h3>用户列表组件</h3>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="javascript:;">用户管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <!-- 搜索区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            class="input-with-select"
            v-model="queryInfo.query"
            clearable
            @clear='getUserList'
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click='getUserList'
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button
            type="primary"
            @click="addDialogVisible = true"
          >
            添加用户
          </el-button>
        </el-col>
      </el-row>
      <!-- 表格区域  、 -->
      <el-table
        border
        stripe
        :data="userList"
        style="width: 100%"
      >
        <!-- 索引列 -->
        <el-table-column
          type="index"
          label="#"
        >
        </el-table-column>
        <el-table-column
          prop="username"
          label="姓名"
          width="180"
        >
        </el-table-column>
        <el-table-column
          prop="email"
          label="邮箱"
          width="280"
        >
        </el-table-column>
        <el-table-column
          prop="mobile"
          label="电话"
          width="280"
        >
        </el-table-column>
        <el-table-column
          prop="role_name"
          label="角色"
          width=""
        >
        </el-table-column>
        <el-table-column
          label="状态"
          width="180"
        >
          <template v-slot='{row}'>
            <el-switch
              @change='changeState(row)'
              v-model="row.mg_state"
              active-color="#13ce66"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
          prop=""
          label="操作"
          width=""
        >
          <template v-slot={row}>

            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click=showEditDialog(row.id)
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click='removeUserById(row.id)'
            ></el-button>
            <el-tooltip
              :enterable="false"
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click='setRole(row)'
              ></el-button>
            </el-tooltip>

          </template>
        </el-table-column>
      </el-table>
      <!-- 分页模块 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="40%"
      @closed='resetFields'
    >
      <!-- 对话框主体区域 -->
      <el-form
        label-width="70px"
        :model='addForm'
        :rules="addFormRules"
        ref='addUserFormRef'
      >
        <el-form-item
          label="用户名"
          prop="username"
        >
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item
          label="密码"
          prop="password"
        >
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item
          label="邮箱"
          prop="email"
        >
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item
          label="手机号"
          prop="mobile"
        >
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>

      </el-form>
      <!-- 对话框底部区域 · -->
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click='addUser'
        >确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑用户对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @close='editDialogCLosed'
    >
      <el-form
        :model="editForm"
        ref='editFormRef'
        :rules='editFormRules'
        label-width="80px"
      >
        <el-form-item label="用户名">
          <el-input
            v-model="editForm.username"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item
          label="邮箱"
          prop="email"
        >
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item
          label="电话"
          prop="mobile"
        >
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          @click="editUser"
        >立即修改</el-button>
        <el-button @click='editDialogVisible=false'>取消</el-button>
      </span>

    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRoleDialogVisible"
      width="50%"
      @close='setRoleDialogClosed'
    >
      <div>
        <p>当前的用户:{{userInfo.username}}</p>
        <p>当前的角色:{{userInfo.role_name}}</p>
        <p>分配新角色:
          <!-- 角色选择下拉框
v-model：设置用户选中角色之后的id绑定数据
-->
          <el-select
            v-model="selectedRoleId"
            placeholder="请选择角色"
          >
            <!-- :label 显示文本，:value 选中值 -->
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>

        </p>
      </div>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="saveRoleInfo"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  props: [],
  data () {
    // 公有数据-------------------****-------------------------
      //验证邮箱的规则
  var checkEmail = (rule, value, cb) => {
    const regEmail = /^\w+@\w+(\.\w+)+$/
    if (regEmail.test(value)) {
      return cb()
    }
    //返回一个错误提示
    cb(new Error('请输入合法的邮箱'))
  }
  //验证手机号码的规则
  var checkMobile = (rule, value, cb) => {
    const regMobile = /^1[34578]\d{9}$/
    if (regMobile.test(value)) {
      return cb()
    }
    //返回一个错误提示
    cb(new Error('请输入合法的手机号码'))
  }
  // ------------私有数据-------------****---------------------- 
    return {
      // -----------------------列表展示数据-----------------------
      queryInfo:{
        query:'',
        pagenum:1,
        pagesize:2
      },
      userList:[],
      total:0,
      // --------------------------添加功能数据---------------
      //  对话框开关
      addDialogVisible:false,
      // 添加用户的表单数据
      addForm:{
        username:'',
        password:'',
        email:'',
        mobile:''
      },
      // -----------------------编辑功能数据------------------
      // 编辑用户的表单信息
      editForm: {
    username: '',
    email: '',
    mobile: ''
},
// --------------------------分配角色功能-----------------------------------
// 分配角色对话框开关
setRoleDialogVisible:false,
 //保存正在操作的那个用户信息
    userInfo:{},
    //保存所有的角色信息
    rolesList:[],
    //保存用户选中的角色id
    selectedRoleId:'',
//修改表单的验证规则对象
editFormRules: {
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        {
        validator: checkEmail,
        message: '邮箱格式不正确，请重新输入',
        trigger: 'blur'
        }
    ],
    mobile: [
        { required: true, message: '请输入手机号码', trigger: 'blur' },
        {
        validator: checkMobile,
        message: '手机号码不正确，请重新输入',
        trigger: 'blur'
        }
    ]
},
      // 编辑对话框显示开关
      editDialogVisible:false,
      // 添加表单的验证规则对象
      addFormRules:{
        username:[
          {required:true,message:'请输入用户名',trigger: 'blur'},
          {min: 3,max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur'}
        ],
   password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        {
          min: 6,
          max: 15,
          message: '用户名在6~15个字符之间',
          trigger: 'blur'
        }
      ],
      email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator:checkEmail, message: '邮箱格式不正确，请重新输入', trigger: 'blur'}
      ],
      mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator:checkMobile, message: '手机号码不正确，请重新输入', trigger: 'blur'}
      ]
      },
    // ----------------  ②编辑功能数据---------------------------- 
         // 编辑对话框显示开关
      editDialogVisible:false,
      // 编辑用户的表单信息
      editForm: {
        username: '',
        email: '',
        mobile: ''
},
//编辑表单的验证规则对象
editFormRules: {
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        {
        validator: checkEmail,
        message: '邮箱格式不正确，请重新输入',
        trigger: 'blur'
        }
    ],
    mobile: [
        { required: true, message: '请输入手机号码', trigger: 'blur' },
        {
        validator: checkMobile,
        message: '手机号码不正确，请重新输入',
        trigger: 'blur'
        }
    ]
},
// -------------------③分配角色数据----------------
// 分配角色对话框开关
setRoleDialogVisible:false,
 //保存正在操作的那个用户信息
    userInfo:{},
    //保存所有的角色信息
    rolesList:[],
    //保存用户选中的角色id
    selectedRoleId:'',
    }
  },
  mounted () {
    this.getUserList()
  },
  methods: {
    async getUserList(){
      const { data: res } = await this.$http.get(`users`, {
        params: this.queryInfo
      }).catch(err=>console.log(err))
  console.log(res);
  if(res.meta.status!==200){ 
    return this.$message.error('获取用户数据失败!')
  }
  this.userList = res.data.users
  this.total = res.data.total
    },
    // 修改状态
 async   changeState(row){
      console.log(row);
    const { data: res } = await this.$http.put(`users/${row.id}/state/${row.mg_state}`, {})
    if(res.meta.status!==200){ return this.$message.error('更新用户状态失败！')}
    this.$message.success('更新用户状态成功!')
    },
    // 监听每页多少条 改变
     handleSizeChange(val) {
          this.queryInfo.pagesize = val;
      console.log(`每页: ${val}条`);
      // 重新获取数据
      this.getUserList()
      },
    // 监听当前页 改变
      handleCurrentChange(val) {
        this.queryInfo.pagenum = val;
        console.log(`当前页: ${val}`);
              this.getUserList()

      },
      // 添加用户确认
      addUser(){
        // 预校验表单内容
        this.$refs.addUserFormRef.validate(async valid=>{
          if(!valid){
            return this.$message.error('添加用户失败！')
          }
          const { data: res } = await this.$http.post('users',this.addForm)
          this.$message.success('添加用户成功！')
          this.addDialogVisible = false
          this.getUserList()
        })
      }      ,
      // 对话框关闭完成后的回调
      resetFields(){
        console.log(this.$refs);
                this.$refs.addUserFormRef.resetFields();
      }
      ,
      // 编辑功能
      async    showEditDialog(id){
        const { data: res } = await this.$http.get('users/'+id)
        // 如果添加失败提示信息
        if(res.meta.status !== 200){ return this.$message.error('获取用户信息失败!')}
        // 获取到的数据保存到editForm中
        this.editForm = res.data
        // 显示弹出层
        this.editDialogVisible =true
      },
      // 监听对话框关闭 重置表单
      editDialogCLosed(){
        this.$refs.editFormRef.resetFields()
      },
      // 编辑提交功能

      editUser(){
        // 预校验
        this.$refs.editFormRef.validate(async valid=>{
          if(!valid)return this.$message.error('请填写完整用户信息')
          // 发送请求修改用户信息
          const { data: res} = await this.$http.put('users/'+this.editForm.id, this.editForm
) 
if(res.meta.status!==200){ return this.$message.error('修改用户失败')}
this.$message.success('修改用户成功')
console.log(res);
this.editDialogVisible=false;
// 重新渲染页面
this.getUserList()
        })
      },
      // 删除用户信息
       removeUserById(id){
        this.$confirm('确认删除?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          callback:async action => {
            if(action === 'confirm'){
          const { data: res } =        await this.$http.delete(`users/${id}`)
          if(res.meta.status !== 200){ return this.$message.error('删除失败')}
          this.$message.success('删除成功！')
          this.getUserList()        
            }
          }
        })
        
      },
      // 分配角色功能
  async    setRole(userInfo){
        this.setRoleDialogVisible=true
 //保存起来以供后续使用
      this.userInfo = userInfo;
      //获取所有的角色信息，以备下拉列表使用
      //发送请求获取角色
      const { data: res } = await this.$http.get('roles')
      //判断如果获取失败，就做提示
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败')
      // console.log(res.data);
      this.rolesList = res.data;
      },
      // 分配角色确定
       async saveRoleInfo(){
         //当用户点击确定按钮之后
      //判断用户是否选择了需要分配的角色
      if(!this.selectedRoleId){
        return this.$message.error('请选择需要分配的角色')
      }
       //发送请求完成分配角色的操作
      const {data:res} = await this.$http.put(`users/${this.userInfo.id}/role`,{rid:this.selectedRoleId})
       //判断如果删除失败，就做提示
      if (res.meta.status !== 200)
        return this.$message.error('分配角色失败')
         this.$message.success('分配角色成功')
      this.getUserList();
      //关闭对话框
      this.setRoleDialogVisible = false
       },
        setRoleDialogClosed(){
      //当关闭对话框的时候，重置下拉框中的内容
      this.selectedRoleId = ''
      this.userInfo = {}
    }
  }
}
</script>
<style lang="less" scoped>

</style>